<?php

require('baseModel.php');
require_once("DatabaseUtils.php");

/**
 * This class is the model for the category table in the database.
 * It is used to access the database table directly.  The category 
 * database should not be accessed anywhere else in the project.
 * 
 * @author Matt Makins
 * 
 */
class Category extends BaseModel{
   
	private $name;   
	private $id;
   
   	public function Category($name, $id){
   	
   		$this->name = $name;	
   		$this->id = $id;
   	}
   	
	/**
	 * adds a new category to the database
	 * 
	 * @param $name
	 */
   	public static function addCategory($name){
   	
   		//TODO: also validate presence of name
   		if(Category::validate_uniqueness_of($name, "category")){
   			
   			Category::connect();
   			mysql_query("INSERT INTO category(name) VALUES (' $name ')");
   			mysql_close();
   			return true;
   		}
   		return false;	
   	}
   	
   	/**
   	 * finds all of the categories in the db, and returns them as
   	 * Category objects
   	 * 
   	 * @return array of Category objects
   	 *
   	 */
   	public static function findAllCategories(){
   		
   		Category::connect();
   		$categories = array();
   		$find = mysql_query("SELECT * FROM category ORDER BY name DESC");
   		while ($row = mysql_fetch_array($find)){
   			array_push($categories, new Category($row['name'], $row['id']));
   		}
   		return $categories;
   	} 
   	
   	function editCategory($id, $name){
   		
   		$this->connect();
   		mysql_query("UPDATE category set name = ' $name' WHERE id = ' $id'");
   		mysql_close();
   	}
   	
   	/**
   	 * deletes the category from the database
   	 * 
   	 * @param id
   	 */
   	function deleteCategory($id){
   		
   		$this->connect();
   		mysql_query("DELETE FROM category WHERE id = '$id'");
   		mysql_close();
   	}
    	
	/**
	 * returns the number of categories present in the database
	 * 
	 * @return int
	 */
 	public static function getNumberOfCategories(){
 		
		if(DatabaseUtils::databaseExists() && DatabaseUtils::tableExists(DB_CATEGORY_TABLE)){ 		
 			Category::connect();
 			return mysql_num_rows(mysql_query("SELECT * FROM category"));
		}
		return 0;
 	}

	public function getName(){
		return $this->name;
	}
	
	public function getId(){
		return $this->id;
	}
 }
?>
